package api

import (
	"awesomeProject/internal/service"
	"awesomeProject/pkg/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PostController struct {
	postService service.PostService
}

func NewPostController(postService service.PostService) *PostController{
	return &PostController{
		postService: postService,
	}
}

// CreatePost 创建帖子
func (pc *PostController) CreatePost(c *gin.Context){
	userID:=utils.GetUserIDFromContext(c)
	var req service.CreatePostRequest
	if err:=c.ShouldBindJSON(&req);err!=nil{
		c.JSON(http.StatusBadRequest,gin.H{"error":err.Error()})
		return
	}
	post,err:=pc.postService.CreatePost(c,userID,&req)
	if err!=nil{
		utils.HandleError(c,err)
		return
	}
	c.JSON(http.StatusCreated,gin.H{"post":post,})
}

// GetPost 获取帖子
func (pc *PostController)GetPost(c *gin.Context){
	postID,err:=strconv.ParseUint(c.Param("id"),10,32)
	if err!=nil{
		c.JSON(http.StatusBadRequest,gin.H{"error":err.Error()})
		return
	}
	post,err:=pc.postService.GetPost(c,uint(postID))
	if err!=nil{
		utils.HandleError(c,err)
		return
	}
	c.JSON(http.StatusOK,gin.H{"post":post})
}

// UpdatePost 更新帖子
func (pc *PostController) UpdatePost(c *gin.Context){
	userID:=utils.GetUserIDFromContext(c)
	postID,err:=strconv.ParseUint(c.Param("id"),10,32)
	if err!=nil{
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
		return
	}
	var req service.UpdatePostRequest
	if err=c.ShouldBindJSON(&req);err!=nil{
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	err=pc.postService.UpdatePost(c,userID,uint(postID),&req)
	if err!=nil{
		utils.HandleError(c,err)
		return
	}
	c.JSON(http.StatusOK,gin.H{"message":"Post updated successfully"})
}

// DeletePost 删除帖子
func (pc *PostController) DeletePost(c *gin.Context){
	userID:=utils.GetUserIDFromContext(c)
	postID,err:=strconv.ParseUint(c.Param("id"),10,32)
	if err!=nil{
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
		return
	}
	err=pc.postService.DeletePost(c,userID,uint(postID))
	if err!=nil{
		utils.HandleError(c,err)
		return
	}
	c.JSON(http.StatusOK,gin.H{"message":"Post deleted successfully"})
}

func (pc *PostController) ListPosts(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	keyword := c.Query("keyword")
	sortBy := c.DefaultQuery("sort_by", "created_at")
	order := c.DefaultQuery("order", "desc")
	
	req := &service.PostListRequest{
		Page:     page,
		PageSize: limit,
		Keyword:  keyword,
		SortBy:   sortBy,
		Order:    order,
	}
	
	posts, total, err := pc.postService.GetPostList(c, req)
	if err != nil {
		utils.HandleError(c, err)
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"posts": posts,
		"total": total,
		"page":  page,
		"limit": limit,
	})
}

func (pc *PostController) GetPostsByCategory(c *gin.Context) {
	categoryID, err := strconv.ParseUint(c.Param("categoryId"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid category ID"})
		return
	}
	
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
	
	posts, total, err := pc.postService.GetPostsByCategory(c, uint(categoryID), page, limit)
	if err != nil {
		utils.HandleError(c, err)
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"posts": posts,
		"total": total,
		"page":  page,
		"limit": limit,
	})
}

// SearchPosts 搜索帖子 - 通过ListPosts的keyword参数实现
// 客户端可以使用 GET /posts?keyword=xxx 来搜索

func (pc *PostController) AddFavorite(c *gin.Context) {
	userID := utils.GetUserIDFromContext(c)
	postID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
		return
	}
	
	err = pc.postService.FavoritePost(c, userID, uint(postID))
	if err != nil {
		utils.HandleError(c, err)
		return
	}
	
	c.JSON(http.StatusOK, gin.H{"message": "Post added to favorites"})
}

func (pc *PostController) RemoveFavorite(c *gin.Context) {
	userID := utils.GetUserIDFromContext(c)
	postID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
		return
	}
	
	err = pc.postService.UnfavoritePost(c, userID, uint(postID))
	if err != nil {
		utils.HandleError(c, err)
		return
	}
	
	c.JSON(http.StatusOK, gin.H{"message": "Post removed from favorites"})
}

// GetUserFavorites 获取用户收藏的帖子列表
func (pc *PostController) GetUserFavorites(c *gin.Context) {
	// 从URL参数获取用户ID
	userIDStr := c.Param("user_id")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
		return
	}

	// 获取分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	// 调用服务层获取用户收藏的帖子
	posts, total, err := pc.postService.GetUserFavorites(c, uint(userID), page, pageSize)
	if err != nil {
		utils.HandleError(c, err)
		return
	}

	// 返回分页结果
	c.JSON(http.StatusOK, PaginatedResponse{
		Data:       posts,
		Total:      total,
		Page:       page,
		PageSize:   pageSize,
		TotalPages: (total + int64(pageSize) - 1) / int64(pageSize),
	})
}
